package com.contacts.controller;


import com.contacts.pojo.User;
import com.contacts.result.Result;
import com.contacts.service.UserService;
import com.contacts.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@Slf4j
@RequestMapping("/user/login")
@Api(tags = "登录接口")
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping
    @ApiOperation("Login")
    public Result login(@RequestBody User user){
        log.info("用户登录"+user);
        User u = userService.login(user);
        //判断登录用户是否存在
        if (u != null){
            //自定义信息
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getUserId());
            claims.put("username",u.getUserName());
            //生成token令牌
            String token = JwtUtil.createJWT("loginintocontactlist",43200000L,claims);
            return Result.success(token);
        }
        return Result.error("用户名或密码错误");
    }
}
